#!/bin/bash

# 定义日志文件
LOG_FILE="$HOME/install_grpc_java.log"

echo "This script will install grpc-java v1.56.0 and its dependencies on your system. The log of this installation process will be saved in $LOG_FILE"

# 定义工作目录
WORK_DIR="$HOME/grpc_java_installation"

# 创建工作目录
mkdir -p "$WORK_DIR"
mkdir -p "$WORK_DIR/patches"
cp ../patches/grpc-patch.patch "$WORK_DIR/patches/"

# 保存当前工作目录
pushd . >/dev/null
cd "$WORK_DIR" || exit

# 安装编译依赖
sudo yum install -y g++ bazel

# 提前下载 Gradle
wget -c https://services.gradle.org/distributions/gradle-7.6-bin.zip

# 下载并解压grpc-java源码
wget -c https://github.com/grpc/grpc-java/archive/refs/tags/v1.56.0.tar.gz
tar -zxf v1.56.0.tar.gz
rm v1.56.0.tar.gz
cd grpc-java-1.56.0 || exit

# 应用 patch
patch -p1 <../patches/grpc-patch.patch

# 替换命名
sed -i "s,@HOME@,${HOME},g" build.gradle
# 替换资源位置
sed -i "s|https\\\\://services.gradle.org/distributions|file://${WORK_DIR}|g" gradle/wrapper/gradle-wrapper.properties

# 移植 protobuf-25.4
mkdir -p /var/tmp/protobuf-cache/25.4/Linux-riscv64/bin
pushd /var/tmp/protobuf-cache/25.4/Linux-riscv64/bin/ || exit
sudo cp /usr/local/bin/protoc ./
popd || exit

# 编译安装grpc-java
SKIP_TESTS=true ARCH=riscv64 ./buildscripts/kokoro/unix.sh
mvn install:install-file -DgroupId=io.grpc -DartifactId=protoc-gen-grpc-java -Dversion=1.56.0 -Dclassifier=linux-riscv64 -Dpackaging=exe -Dfile=mvn-artifacts/io/grpc/protoc-gen-grpc-java/1.56.0/protoc-gen-grpc-java-1.56.0-linux-riscv64.exe

if [ $? -ne 0 ]; then
    echo "grpc-java installation failed" | tee -a "$LOG_FILE"
    exit 1
else
    echo "grpc-java installation succeeded" | tee -a "$LOG_FILE"
fi

# 清理源码目录
rm -rf "$WORK_DIR"

# 恢复之前的工作目录
popd >/dev/null || exit

echo "This script is finished" | tee -a "$LOG_FILE"
